package io.gitee.zhangbinhub.admin.route.conf

import io.gitee.zhangbinhub.acp.boot.tools.EnvironmentTools
import io.gitee.zhangbinhub.admin.common.constant.RouteConstant
import org.springframework.boot.SpringApplication
import org.springframework.boot.env.EnvironmentPostProcessor
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.util.MimeTypeUtils

/**
 * @author zhang by 17/05/2019
 * @since JDK 11
 */
class RouteUpdateEnvironmentPostProcessor : EnvironmentPostProcessor {
    private val defaultPropertiesName = "acpCloudRouteDefaultProperties"

    override fun postProcessEnvironment(environment: ConfigurableEnvironment?, application: SpringApplication?) {
        val default: MutableMap<String, Any> = HashMap()
        "spring.cloud.stream.bindings.${RouteConstant.UPDATE_ROUTE_OUTPUT}".let { prefix ->
            environment!!.getProperty("$prefix.destination", RouteConstant.UPDATE_ROUTE_DESCRIPTION)
                .let { destination ->
                    if (destination == RouteConstant.UPDATE_ROUTE_OUTPUT) {
                        RouteConstant.UPDATE_ROUTE_DESCRIPTION
                    } else {
                        destination
                    }
                }.let { destination ->
                    default["$prefix.destination"] = destination
                    default["$prefix.contentType"] = MimeTypeUtils.APPLICATION_JSON_VALUE
                    EnvironmentTools.addOrReplaceProperty(
                        environment.propertySources,
                        default,
                        defaultPropertiesName,
                        false
                    )
                }
        }
    }
}
